package com.ruoyi.web.controller.app;

import com.ruoyi.common.annotation.IgnoreAuth;
import com.ruoyi.common.constant.ApiConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessCode;
import com.ruoyi.framework.shiro.service.SysLoginService;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.util.TokenUtil;
import com.ruoyi.system.domain.SysToken;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysTokenService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(value="APP用户登录信息",tags={"APP用户登录信息接口"})
@RequestMapping("app/login")
@RestController
public class AppLoginController extends BaseController {

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysTokenService iSysTokenService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private ISysConfigService configService;

    @IgnoreAuth //不需要token验证
    @PostMapping("/login-by-username")
    @ApiOperation(value = "根据登录名称登录接口",response=AjaxResult.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="username",value="登录名",required=true ),
            @ApiImplicitParam(name="password",value="密码",required=true)
    })
    public AjaxResult loginByUserName(HttpServletRequest request, @RequestParam String username, @RequestParam String password){

        SysUser sysUser = loginService.login(username,password);
        Map<String, Object> token = iSysTokenService.createToken(sysUser.getUserId());
        //request.getSession().setAttribute(ApiConstants.LOGIN_USER_KEY,sysUser.getUserId());
        return  AjaxResult.success(token);

    }


    @IgnoreAuth //不需要token验证
    @PostMapping("/login-by-face")
    @ApiOperation(value = "人脸识别登录获取token",response=AjaxResult.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value="人脸识别返回token",required=true ),
            @ApiImplicitParam(name="idcard",value="身份证",required=true),
            @ApiImplicitParam(name="jh",value="警号",required=true),
            @ApiImplicitParam(name="name",value="姓名",required=true)
    })
    public AjaxResult loginByFace(@RequestParam String token, @RequestParam String idcard, @RequestParam String jh, String name){

        //如果token有效直接返回
        SysToken sysToken = iSysTokenService.selectSysTokenByToken(token);
        if (sysToken != null && sysToken.getExpireTime().getTime() > System.currentTimeMillis()) {
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("expireTime", sysToken.getExpireTime());
            return  AjaxResult.success(map);
        }



        SysUser user = iSysUserService.selectUserByLoginName(jh);
        if(null==user){   //用户第一次登录，初始化账户
            SysUser newUser = new SysUser();
            newUser.setUserName(name);
            newUser.setLoginName(jh);
            newUser.setIdCard(idcard);
            newUser.setSalt(ShiroUtils.randomSalt());
            String initPassword = configService.selectConfigByKey("sys.user.initPassword");
            newUser.setPassword(passwordService.encryptPassword(newUser.getLoginName(), initPassword, newUser.getSalt()));
            newUser.setCreateBy("admin");
            iSysUserService.insertUser(newUser);
            Map exMap = createToken(token,null,newUser.getUserId());
            return  AjaxResult.success(exMap);
        }

        SysToken exToken = iSysTokenService.selectSysTokenByUserId(user.getUserId());
        Map exMap = createToken(token,exToken,user.getUserId());
        return  AjaxResult.success(exMap);

    }

    private Map<String, Object> createToken(String strToken,SysToken token,Long userId){

        //当前时间
        Date now = new Date();
        //过期时间
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 30);
        Date expireTime = cal.getTime();

        if (token == null) {
            token = new SysToken();
            token.setUserId(userId);
            token.setToken(strToken);
            token.setUpdateTime(now);
            token.setExpireTime(expireTime);
            //保存token
            iSysTokenService.insertSysToken(token);
        } else {
            token.setToken(strToken);
            token.setUpdateTime(now);
            token.setExpireTime(expireTime);
            //更新token
            iSysTokenService.updateSysToken(token);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", strToken);
        map.put("expireTime", expireTime);

        return map;

    }


}
